
package cjos.conexionBD;

import java.sql.*;

/**
 *
 * @author Jos
 */
public class ConexionMySql {

	public void conexionDirectaMySql() {
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		String url ="jdbc:mysql://localhost/test";
		String usuario ="";
		String pass ="";
		try {                                                       System.out.println("Intentando cargar el conector a MySql ...");
			Class.forName("com.mysql.jdbc.Driver");                 System.out.println("Conectando a la base MySql...");
			con = DriverManager.getConnection(url,usuario, pass);   System.out.println("Conexion a BD establecida MySql\n");
						
			StringBuilder query = new StringBuilder();
			query.append("SELECT 'Hola MySql' as saludo FROM dual");
			
			stmt = con.prepareStatement(query.toString());
			rs = stmt.executeQuery();
			while (rs.next()) {
				System.out.println(rs.getString(1));
			}

		} catch (SQLException ex) {
			System.out.println("Error de mysql");
			System.out.println("SQLState: " + ex.getSQLState());
			System.out.println("SQLErrorCode: " + ex.getErrorCode());
			ex.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			System.out.println("Se produjo un error inesperado: " + e + " \n"+ e.getMessage());
		} finally {
			try {
				if(rs!=null) rs.close();
				if(stmt!=null) stmt.close();
				if(con!=null)con.close();			
			} catch (Exception e) {e.printStackTrace();}
		}

	}

	public static void main(String arg[]) {
		ConexionMySql c = new ConexionMySql();
		c.conexionDirectaMySql();
	}
}
